package vn.dinhnp.tourismdict;

import java.io.IOException;
import java.util.ArrayList;

import vn.dinhnp.model.DetailPhrase;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class MyArrayAdapter extends ArrayAdapter<DetailPhrase> {

	protected static DataBaseHelper myDbHelper;
	Activity context = null;
	ArrayList<DetailPhrase> myArray = null;
	int layoutId;

	public MyArrayAdapter(Activity context, int layoutId,
			ArrayList<DetailPhrase> arr) {
		super(context, layoutId, arr);
		this.context = context;
		this.layoutId = layoutId;
		this.myArray = arr;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = context.getLayoutInflater();
		convertView = inflater.inflate(layoutId, null);
		if(myArray.size()>0 && position>=0)
		 {
		 final TextView txtdisplay=(TextView)convertView.findViewById(R.id.txtitem);
		 final DetailPhrase emp=myArray.get(position);
		 txtdisplay.setText(emp.English);
		 final ImageButton imgitem=(ImageButton)convertView.findViewById(R.id.chkitem);
		 if(emp.favourite==1)
		 imgitem.setBackgroundResource(R.drawable.favourite);
		 else
			 imgitem.setBackgroundResource(R.drawable.non_favourite);
		 
		 imgitem.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(emp.favourite==1)
				{
					try {
			        	Log.e("database", "Bắt đầu mở csdl");
						myDbHelper= new DataBaseHelper(getContext());
						myDbHelper.openDataBase();	
						Log.e("database", "Mở csdl thành công");
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					myDbHelper.exeSql(" update phrase set favorite=0 where _id="+emp.Id);
					myDbHelper.close();
					imgitem.setBackgroundResource(R.drawable.non_favourite);
					emp.favourite=0;
				}
				else
				{
					try {
			        	Log.e("database", "Bắt đầu mở csdl");
						myDbHelper= new DataBaseHelper(getContext());
						myDbHelper.openDataBase();	
						Log.e("database", "Mở csdl thành công");
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					myDbHelper.exeSql(" update phrase set favorite=1 where _id="+emp.Id);
					myDbHelper.close();
					imgitem.setBackgroundResource(R.drawable.favourite);
					emp.favourite=1;
				}
			}
		});
		 }
		
		
		
		return convertView;
	}

}
